package com.cyj.qqclient.service;

import com.cyj.qqcommon.Message;
import com.cyj.qqcommon.MessageType;

import java.io.*;
import java.net.Socket;
import java.util.Date;

public class ClientConnectServerThread extends Thread implements Serializable {
    private Socket socket;
    public ClientConnectServerThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        while(true){
            System.out.println("客户端线程，等待从服务器接收消息。。。。");
            try {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) ois.readObject();
                if(message.getMessageType().equals(MessageType.MESSAGE_RET_OFFLINE_FRIEND)){
                    String[] onlineUsers = message.getContent().split(" ");
                    System.out.println("=============当前在线用户=============");
                    for(String onlineUser : onlineUsers){
                        System.out.println("用户："+onlineUser);
                    }
                }else if (message.getMessageType().equals(MessageType.MESSAGE_COMM_MES)){
                    System.out.println("\n"+message.getSender()+"对"+message.getGetter()+"说："+
                            message.getContent()+message.getSendtime());
                } else if (message.getMessageType().equals(MessageType.MESSAGE_TOALL_MES)) {
                    System.out.println("\n"+message.getSender()+"对大家说："+message.getContent()+message.getSendtime());
                }else if (message.getMessageType().equals(MessageType.MESSAGE_FILE_MES)){
                    System.out.println("\n"+message.getSender()+"给 "+message.getGetter()+"发文件："+message.getSrc()+"到目录："+message.getDest()+
                            "\n"+new Date().toString());

                    FileOutputStream fos = new FileOutputStream(message.getDest());
                    fos.write(message.getFileBytes());
                    fos.close();
                    System.out.println("\n 文件保存成功");
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public Socket getSocket(){
        return socket;
    }

}
